import datetime
import json
import time

import cv2
import numpy as np
from flask import Flask
from flask_cors import CORS

from GlobalValues import globalVal
from camera import CameraLive
from controller import FunctionController

from util import ReadConfig

app = Flask(__name__)
CORS(app, supports_credentials=True)
app.register_blueprint(FunctionController.equipment, url_prefix='/function/')


def MfVideo():
    if not globalVal.vid.isOpened():
        raise IOError("Couldn't open webcam or video")
    while globalVal.vid.isOpened():
        return_value, frame = globalVal.vid.read()

        frame = add_timestamp_wm(frame)
        # 保持最后一帧
        globalVal.mfVideo_rs = frame
        globalVal.live_frame = frame
        # 原始图片推入队列中
        globalVal.frame_queue.put(frame)

        # 负责移除队列中的旧图
        globalVal.frame_queue.get() if globalVal.frame_queue.qsize() > 1 else time.sleep(0.01)


def add_timestamp_wm(img):
    t = time.time()
    ts = int(round(t * 1000))
    ts_str = str(ts)
    # 块大小
    block_size = len(img[0]) // 13
    block_height = 4
    for i in range(0, len(ts_str)):
        number = ts_str[i]
        color_number = 255 // 10 * int(number)
        block = np.zeros([block_height, block_size, 3], np.uint8)
        block[::, ::, ::] = color_number
        img[0:block_height, i * block_size:i * block_size + block_size] = block
    font = cv2.FONT_HERSHEY_SIMPLEX
    datet = str(datetime.datetime.now())
    frame = cv2.putText(img, datet, (10, 50), font, 0.8,
                        (255, 255, 0), 2, cv2.LINE_AA)
    return frame


if __name__ == '__main__':
    ReadConfig.readConfig()
    globalVal.mfVideo_future = globalVal.pool.submit(MfVideo)
    # globalVal.mfVideo_future = globalVal.pool.submit(CameraLive.Video)
    app.run(host='0.0.0.0', port=5001)
